﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace DienThoai
{
    
    
    /// <summary>
    /// Interaction logic for BillForm.xaml
    /// </summary>
    public partial class BillForm : Window
    {
        Bill bill ;

        public string UserName;
        public BillForm()
        {
            InitializeComponent();
            comboBoxSearchType.Items.Add("Điện Thoại");
            comboBoxSearchType.Items.Add("Phụ Kiện");
            
        }

        /// <summary>
        /// Handle event when main form is loaded
        /// </summary>
        /// <param name="sender">Object that sends this event</param>
        /// <param name="e">Event argument</param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Utility u = new Utility();
            u.getProductDataGrid(dgTK);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgTK_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            BillDetail billDetail = new BillDetail();
            Product choosenP = dgTK.SelectedItem as Product;
            string maxQuantity = choosenP.Quantity.ToString();
            BuyingQuantity f = new BuyingQuantity(maxQuantity);
            f.ShowDialog();
            if (f.Quantity > 0)
            {
                billDetail.ProductID = choosenP.ProductID;
                billDetail.Amount = f.Quantity;
                dgProduct.Items.Add(billDetail);
                choosenP.Quantity -= f.Quantity;
            }
            
            
         //   lbSum.Content = 
        }

        private void btPay_Click(object sender, RoutedEventArgs e)
        {
            Utility u = new Utility();
            DienThoaiDataContext db = new DienThoaiDataContext();
            if (dgProduct.Items.Count != 0)
            {

                bill = new Bill();
                BillDetail detail = new BillDetail();
                //Bill            
                bill.BillID = getID();
                
                bill.SellDate = DateTime.Today;

                if (lbMaKH.Content.ToString() != "")
                    bill.CustomerID = lbMaKH.Content.ToString();


                db.Bills.InsertOnSubmit(bill);
                bill.TotalPrice = double.Parse(lbSum.Content.ToString());
                //Bill Detail
                foreach (var item in dgProduct.Items)
                {
                    detail = item as BillDetail;
                    detail.BillID = bill.BillID;
                    
                    db.BillDetails.InsertOnSubmit(detail);

                    var query = from i in db.Products
                                where i.ProductID == detail.ProductID
                                select i;
                    foreach (var i in query)
                        i.Quantity -= (int)detail.Amount;
                }
                
                
                db.SubmitChanges();
                //refresh the dgTK
                u.getProductDataGrid(dgTK);
                //clear dgProduct for the next bill.

                while (dgProduct.Items.Count > 0)
                {
                    dgProduct.Items.RemoveAt(dgProduct.Items.Count - 1);
                }
                
            }
            else
                MessageBox.Show("Chưa chọn sản phẩm.");
        }
        private string getID()
        {
            DienThoaiDataContext db = new DienThoaiDataContext();
            string ID = "";

            var query = from i in db.Bills
                        select i.BillID;

            if (query.Count() == 0)
                ID = "B00001";
            else
            {
                int temp = 0;
                foreach (var i in query)
                    temp = int.Parse(i.ToString().Substring(2)) + 1;
                if (temp < 10)
                    ID = "B0000" + temp.ToString();
                else if (temp < 100)
                    ID = "B000" + temp.ToString();
                else if (temp < 1000)
                    ID = "B00" + temp.ToString();
                else if (temp < 10000)
                    ID = "B0" + temp.ToString();
                else
                    ID = "B" + temp.ToString();
            }
            return ID;
        }

        private void btDelete_Click(object sender, RoutedEventArgs e)
        {
            Product restoreProduct = new Product();
            BillDetail deletedProduct = dgProduct.SelectedItem as BillDetail;
            if (dgProduct.SelectedItem != null)
            {
                foreach (var item in dgTK.Items)
                {
                    restoreProduct = item as Product;
                    if (restoreProduct.ProductID == deletedProduct.ProductID)
                        restoreProduct.Quantity += (int)deletedProduct.Amount;
                }
                dgProduct.Items.Remove(dgProduct.SelectedItem);
            }
            else
                MessageBox.Show("Chưa chọn sản phẩm.");
        }

        private void btDeleteAll_Click(object sender, RoutedEventArgs e)
        {
            Product restoreProduct = new Product();
            BillDetail deletedProduct = new BillDetail();
            while (dgProduct.Items.Count > 0)
            {
                // lấy ra sản phẩm cần thay đổi thông tin
                deletedProduct = dgProduct.Items[dgProduct.Items.Count - 1] as BillDetail;                
                foreach (var item in dgTK.Items)
                {
                    restoreProduct = item as Product;
                    if (restoreProduct.ProductID == deletedProduct.ProductID)
                        restoreProduct.Quantity += (int)deletedProduct.Amount;
                }
                dgProduct.Items.RemoveAt(dgProduct.Items.Count - 1);
            }
        }


        private void btSum_Click(object sender, RoutedEventArgs e)
        {
            DienThoaiDataContext db = new DienThoaiDataContext();
            BillDetail detail = new BillDetail();
            lbSum.Content = 000;
            foreach (var item in dgProduct.Items)
            {

                detail = item as BillDetail;
                var query = from i in db.Products
                            where i.ProductID == detail.ProductID
                            select i.Price;
                foreach (var i in query)
                {
                    if (lbFullName.Content.ToString() == "Name")
                        lbSum.Content = int.Parse(lbSum.Content.ToString()) + detail.Amount * i;
                    else
                        lbSum.Content = int.Parse(lbSum.Content.ToString()) + detail.Amount * i * ( (100 - float.Parse(lbRate.Content.ToString()))/100);
                }
            }
        }
        private void Window_GotFocus(object sender, RoutedEventArgs e)
        {
            DienThoaiDataContext db = new DienThoaiDataContext();
            BillDetail detail = new BillDetail();
            lbSum.Content = 000;
            foreach (var item in dgProduct.Items)
            {

                detail = item as BillDetail;
                var query = from i in db.Products
                            where i.ProductID == detail.ProductID
                            select i.Price;
                foreach (var i in query)
                {
                    if (lbFullName.Content.ToString() == "Name")
                        lbSum.Content = int.Parse(lbSum.Content.ToString()) + detail.Amount * i;
                    else
                        lbSum.Content = int.Parse(lbSum.Content.ToString()) + detail.Amount * i * ((100 - float.Parse(lbRate.Content.ToString())) / 100);
                }
            }
        }

        private void btCustomerCode_Click(object sender, RoutedEventArgs e)
        {
            DienThoaiDataContext db = new DienThoaiDataContext();
            var customer = from i in db.Customers
                           where i.PersonID == lbMaKH.Content.ToString()
                           select i;

            ConfirmID f = new ConfirmID();
            f.ShowDialog();
            var query = from i in db.Customers
                        where i.PersonID == f.Code
                        select i;
            if (query.Count() == 0)
                MessageBox.Show("Khách hàng không tồn tại trong CSDL.");
            else
            {
                foreach (var i in query)
                {
                    lbFullName.Content = i.Person.Fullname;
                    lbDOB.Content = i.Person.DOB;
                    lbAddress.Content = i.Person.Address;
                    lbPhone.Content = i.Person.Phone;
                    lbType.Content = i.Kind.Detail;
                    lbTotalAmount.Content = i.TotalAmount;
                    lbMaKH.Content = i.PersonID;
                    lbRate.Content = i.Kind.rate;
                }
                foreach (var i in customer)
                {
                    i.TotalAmount = i.TotalAmount + float.Parse(lbSum.Content.ToString()) * ((100 - float.Parse(lbRate.Content.ToString())) / 100);
                    db.SubmitChanges();
                }
            }
        }

        private void btTK_Click(object sender, RoutedEventArgs e)
        {
            Utility u = new Utility();
            Product product_in_TK = new Product();
            BillDetail product_in_BD = new BillDetail();
            if (txtTK.Text == "" && comboBoxSearchType.SelectedIndex == 0)
                u.getPhoneDataGrid(dgTK);
            else if (txtTK.Text == "" && comboBoxSearchType.SelectedIndex == 1)
                u.getAccessoryDataGrid(dgTK);
            else if (txtTK.Text != "" && comboBoxSearchType.SelectedIndex == 0)
                u.getPhoneDataGrid(dgTK, txtTK.Text);
            else if (txtTK.Text != "" && comboBoxSearchType.SelectedIndex == 1)
                u.getAccessoryDataGrid(dgTK, txtTK.Text);
            if (dgProduct.Items.Count != 0)
            {
                foreach (var item in dgProduct.Items)
                {
                    product_in_BD = item as BillDetail;
                    foreach (var item1 in dgTK.Items)
                    {
                        product_in_TK = item1 as Product;
                        if (product_in_TK.ProductID == product_in_BD.ProductID)
                            product_in_TK.Quantity -= (int)product_in_BD.Amount;
                    }
                }
            }
        }
    }
}
